<template>
  <view class="min-h-screen bg-gradient-to-br from-blue-500 via-purple-600 to-pink-500 p-[40rpx]">
    <!-- 顶部图标和标题 -->
    <view class="text-center mb-[80rpx] pt-[40rpx]">
      <view
        class="w-[120rpx] h-[120rpx] mx-auto mb-[32rpx] bg-white bg-opacity-20 rounded-full flex items-center justify-center">
        <IconFont name="dongdong" size="60" color="#ffffff"></IconFont>
      </view>
      <text class="block text-[48rpx] font-bold text-white mb-[16rpx]">健康码注册</text>
      <text class="block text-[28rpx] text-white text-opacity-80">请填写您的个人信息完成注册</text>
    </view>

    <!-- 表单容器 -->
    <view class="bg-white rounded-[32rpx] p-[48rpx] shadow-xl shadow-black shadow-opacity-10">
      <!-- 姓名输入 -->
      <view class="mb-[48rpx]">
        <view class="flex items-center mb-[20rpx]">
          <text class="text-[#ff4757] mr-[8rpx] text-[28rpx]">*</text>
          <text class="text-[32rpx] font-semibold text-[#333333]">姓名</text>
        </view>
        <view class="relative">
          <nut-input v-model="formData.name" placeholder="请输入您的真实姓名" clearable :maxlength="20"
            class="w-full h-[88rpx] bg-[#f8f9fa] border-2 border-[#e9ecef] rounded-[16rpx] px-[24rpx] text-[32rpx] focus:border-[#667eea] transition-all duration-300" />
        </view>
      </view>

      <!-- 身份证输入 -->
      <view class="mb-[48rpx]">
        <view class="flex items-center mb-[20rpx]">
          <text class="text-[#ff4757] mr-[8rpx] text-[28rpx]">*</text>
          <text class="text-[32rpx] font-semibold text-[#333333]">身份证号码</text>
        </view>
        <view class="relative">
          <nut-input v-model="formData.idCard" placeholder="请输入18位身份证号码" clearable :maxlength="18"
            class="w-full h-[88rpx] bg-[#f8f9fa] border-2 border-[#e9ecef] rounded-[16rpx] px-[24rpx] text-[32rpx] focus:border-[#667eea] transition-all duration-300" />
        </view>
      </view>

      <!-- 提示信息 -->
      <view
        class="bg-gradient-to-r from-blue-50 to-purple-50 rounded-[16rpx] p-[32rpx] mb-[48rpx] border-l-4 border-[#667eea]">
        <view class="flex items-start mb-[12rpx]">
          <view class="w-[8rpx] h-[8rpx] bg-[#667eea] rounded-full mt-[16rpx] mr-[16rpx] flex-shrink-0"></view>
          <text class="text-[28rpx] text-[#666666] leading-[44rpx]">请确保信息真实有效，注册后不可修改</text>
        </view>
        <view class="flex items-start">
          <view class="w-[8rpx] h-[8rpx] bg-[#667eea] rounded-full mt-[16rpx] mr-[16rpx] flex-shrink-0"></view>
          <text class="text-[28rpx] text-[#666666] leading-[44rpx]">身份证信息将用于健康码验证</text>
        </view>
      </view>

      <!-- 注册按钮 -->
      <view class="mt-[48rpx]">
        <nut-button type="primary" size="large"
          class="w-full h-[96rpx] bg-gradient-to-r from-[#667eea] to-[#764ba2] border-0 rounded-[48rpx] text-[36rpx] font-bold text-white shadow-lg shadow-[#667eea] shadow-opacity-40 transition-all duration-200"
          :loading="loading" @click="handleRegister">
          {{ loading ? '注册中...' : '立即注册' }}
        </nut-button>
      </view>
      <view class="mt-[48rpx]">
        <nut-button type="primary" size="large"
          class="w-full h-[96rpx] bg-gradient-to-r from-[#667eea] to-[#764ba2] border-0 rounded-[48rpx] text-[36rpx] font-bold text-white shadow-lg shadow-[#667eea] shadow-opacity-40 transition-all duration-200"
          @tap="handleSign">
          生成子客登录链接
        </nut-button>
      </view>
      <view class="mt-[48rpx]">
        <nut-button type="primary" size="large"
          class="w-full h-[96rpx] bg-gradient-to-r from-[#667eea] to-[#764ba2] border-0 rounded-[48rpx] text-[36rpx] font-bold text-white shadow-lg shadow-[#667eea] shadow-opacity-40 transition-all duration-200"
          @tap="handleCreateContract">
          发起电子合同
        </nut-button>
      </view>
      <view class="mt-[48rpx]">
        <nut-button type="primary" size="large"
          class="w-full h-[96rpx] bg-gradient-to-r from-[#667eea] to-[#764ba2] border-0 rounded-[48rpx] text-[36rpx] font-bold text-white shadow-lg shadow-[#667eea] shadow-opacity-40 transition-all duration-200"
          @tap="handleSignContract">
          签署电子合同
        </nut-button>
      </view>
    </view>

    <CodeImg :code="code" v-if="code" />

    <!-- 底部装饰 -->
    <view class="text-center mt-[60rpx]">
      <view class="flex items-center justify-center space-x-[16rpx]">
        <view class="w-[60rpx] h-[2rpx] bg-white bg-opacity-30"></view>
        <text class="text-[24rpx] text-white text-opacity-60">安全可信赖</text>
        <view class="w-[60rpx] h-[2rpx] bg-white bg-opacity-30"></view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'
// import { request } from '@/service/request'
import { CONTENT_TYPE } from '@/constants/service'

import { request } from '@/service/request';
import { IconFont } from '@nutui/icons-vue-taro'
import CodeImg from './code-img.vue'
import { localStg } from '@/utils';
import { useAuthStore } from '@/store';

// const operatorId = '666777888'
const operatorId = '1234567891'

const userStore = useAuthStore();

const code = ref('')

// 页面配置
definePageConfig({
  navigationBarTitleText: '健康码注册'
})

// 表单数据
const formData = reactive({
  name: '',
  idCard: ''
})

onMounted(() => {
  request.post('/health_code/healthCode/getToken', {
    // name: userStore.nurseUser.name,
  }, {
    useErrMsg: true
  }).then((res: any) => {
    console.log("res==== nurse token", res)
    if (userStore.nurseUser.vuid) {
      getHealthCode();
    }
  })
})

// 发起电子合同
const handleCreateContract = () => {
  console.log("handleCreateContract")
  // 改为先声明 signers 数组并逐项赋值
  // const signers: any[] = [{}];
  // signers[0].approverType = "PERSON";
  // signers[0].idCardNumber = "452225198403150039";
  // signers[0].idCardType = "ID_CARD";
  // signers[0].mobile = "17682344707";
  // signers[0].name = "江思志";
  // signers[0].signOrder = 1;

  // const formFields = [{
  //   componentName: "name",
  //   componentValue: "ComponentId_18",
  // }];

  const data = {
    flowName: "健康码注册协议",
    flowDescription: "健康码注册协议描述",
    templateId: "yDtI7UUckp90sii7UCBtkcRegsf8qVHP",
    operatorId: operatorId,
    operatorName: "黎航",
    operatorTel: "15878776250",
    // proxyOrganizationName: "广西安好医院有限公司",
    // proxyOrganizationOpenId: "org_anfine2",
    "signers[0].approverType": "PERSON",
    "signers[0].idCardNumber": "452225198403150039",
    "signers[0].idCardType": "ID_CARD",
    "signers[0].mobile": "17682344707",
    "signers[0].name": "江思志",
    "signers[0].signOrder": 1,

    // "signers[1].approverType": "PERSON",
    // "signers[1].idCardNumber": "452225198403150039",
    // "signers[1].idCardType": "ID_CARD",
    // "signers[1].mobile": "17682344707",
    // "signers[1].name": "黎航",
    // "signers[1].signOrder": 2,

    // "formFields[0].componentName": "name",
    // "formFields[0].componentValue": "ComponentId_18",

  }

  request.post(
    '/tencent_esign/tencent_contract/tencentContractInfo/createFlowByTemplate',
    data,
    {
      contentType: CONTENT_TYPE.formUrlencoded,
      useErrMsg: true
    }
  ).then((res: any) => {
    console.log("res==== nurse sign 电子签", res)
    if (res.success) {
      const obj = JSON.parse(res.success);
      Taro.showToast({
        title: obj.ErrorMessages.join(',') || '创建成功',
        icon: 'none',
        duration: 2000
      })


      // res.url
      // Taro.navigateTo({
      //   url: `/pages/webview/webview?url=${encodeURIComponent(res.success)}`
      // })
    }
    else {
      Taro.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }

  })
}


const handleSignContract = () => {
  console.log("handleSignContract")
}

const handleSign = () => {
  // console.log("handleSign")
  console.log("userStore.nurseUser.id", userStore.nurseUser)
  request.post('/tencent_esign/tencent_contract/tencentContractInfo/getCreateConsoleLoginUrl', {
    operatorId: operatorId,
    operatorName: "黎航",
    operatorTel: "15878776250",
    proxyOrganizationName: "广西安好医院有限公司",
    proxyOrganizationOpenId: "org_anfine2",
  }, {
    contentType: CONTENT_TYPE.formUrlencoded,
    useErrMsg: true
  }).then((res: any) => {
    console.log("res==== nurse sign 电子签", res)
    if (res.success) {
      // res.url
      // Taro.navigateTo({
      //   url: `/pages/webview/webview?url=${encodeURIComponent(res.success)}`
      // })
    }
    else {
      Taro.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }

  })
}

function register() {
  request.post('/health_code/healthCode/getRegquery', {
    // name: userStore.nurseUser.name,
    appMode: "1",
    klx: "1",
    idType: "01",
    name: formData.name,
    idNo: formData.idCard,
    openid: localStg.get('openid')
  }, {
    useErrMsg: true
  }).then((res: any) => {
    console.log("res==== nurse register", res)
    console.log("res.success?.bizContent?.ecContent", res.success?.bizContent?.ecContent)
    if (res.success?.bizContent?.ecContent) {
      code.value = res.success?.bizContent?.ecContent;
    }
    else {
      getHealthCode();
    }
  })
}

function getHealthCode() {
  request.post('/health_code/healthCode/getApply', {
    // name: userStore.nurseUser.name,
    vuid: userStore.nurseUser.vuid,
  }, {
    useErrMsg: true
  }).then((res: any) => {
    console.log("res==== nurse health code", res)
    console.log("res.success?.bizContent?.ecContent 2", res.success?.bizContent?.ecContent)
    if (res.success?.bizContent?.ecContent) {
      code.value = res.success?.bizContent?.ecContent;
    }
  })
}

// 加载状态
const loading = ref(false)

// 身份证号码验证正则
const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/

// 姓名验证
const validateName = (name: string) => {
  if (!name.trim()) {
    return '请输入姓名'
  }
  if (name.trim().length < 2) {
    return '姓名至少需要2个字符'
  }
  if (name.trim().length > 20) {
    return '姓名不能超过20个字符'
  }
  return ''
}

// 身份证验证
const validateIdCard = (idCard: string) => {
  if (!idCard.trim()) {
    return '请输入身份证号码'
  }
  if (idCard.length !== 18) {
    return '身份证号码必须为18位'
  }
  if (!idCardRegex.test(idCard)) {
    return '身份证号码格式不正确'
  }
  return ''
}

// 支持嵌套对象和数组的 form-urlencoded 工具函数
function toFormUrlEncoded(obj: Record<string, any>, prefix = ''): string {
  const str: string[] = [];
  for (const p in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, p)) {
      const k = prefix ? `${prefix}[${p}]` : p;
      const v = obj[p];
      if (typeof v === 'object' && v !== null && !Array.isArray(v)) {
        str.push(toFormUrlEncoded(v, k));
      } else if (Array.isArray(v)) {
        v.forEach((item, i) => {
          if (typeof item === 'object') {
            str.push(toFormUrlEncoded(item, `${k}[${i}]`));
          } else {
            str.push(`${encodeURIComponent(`${k}[${i}]`)}=${encodeURIComponent(item)}`);
          }
        });
      } else {
        str.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
      }
    }
  }
  return str.join('&');
}

// 注册处理
const handleRegister = async () => {
  // 表单验证
  const nameError = validateName(formData.name)
  if (nameError) {
    Taro.showToast({
      title: nameError,
      icon: 'none',
      duration: 2000
    })
    return
  }

  // const idCardError = validateIdCard(formData.idCard)
  // if (idCardError) {
  //   Taro.showToast({
  //     title: idCardError,
  //     icon: 'none',
  //     duration: 2000
  //   })
  //   return
  // }

  register();

}
</script>